# coding=utf-8

nearZero_ = 0.000001


def classify(input, dataSet, k):
    if input == None:
        return None

    if len(dataSet) == 0:
        return None

    if k < 1:
        return None

    # 按距离排序
    distToOutputs = []
    for data in dataSet:
        dist = data[0].distance(input)
        if dist < nearZero_ and dist > -nearZero_:  # 算法优化
            return data[1]
        distToOutputs.append([dist, data[1]])

    distToOutputsSorted = sorted(distToOutputs, key=lambda x: x[0])

    # 获取前k个样例
    dataLength = len(distToOutputsSorted)
    if k > dataLength:
        k = dataLength

    classCount = {}
    for i in range(k):
        output = distToOutputsSorted[i]
        classCount[output[1]] = classCount.get(output[1], 0) + 1

    # 归类到样例最多的那一类
    result = None
    maxCount = 0
    for key, value in classCount.items():
        if value > maxCount:
            maxCount = value
            result = key

    print('Class rate: ' + str(maxCount / k))
    return result

def test(trainSet, testSet, k):
    if trainSet == None:
        return

    if len(trainSet) == 0:
        return

    if testSet == None:
        return

    if len(testSet) == 0:
        return

    if k < 1:
        return
    
    accuracy = 0
    for testData in testSet:
        target = classify(testData[0], trainSet, k)
        print("Current target: " + str(target))
        print("Expect target: " + str(testData[1]))
        if target == testData[1]:
            accuracy += 1
            print('Correct!')
        else:
            print('Wrong!')
        print('---------------------------------------------')
    print('Accuracy: ' + str(accuracy / len(testSet)))
